package com.zhucai.credit.service.impl.transactional;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhucai.credit.bean.CreditInvoice;
import com.zhucai.credit.model.CreditInvoiceEntity;
import com.zhucai.credit.model.CreditRecordEntrity;
import com.zhucai.credit.model.EntAccountEntity;
import com.zhucai.credit.monitor.service.INotificationService;
import com.zhucai.credit.repository.CreditInvoiceRepository;
import com.zhucai.credit.repository.CreditRecordRepository;
import com.zhucai.credit.repository.EntAccountRepository;
import com.zhucai.credit.service.InvoiceService;
import com.zhucai.credit.utils.SqlResultUtil;
import com.zhucai.credit.valid.invoice.InviceValidResult;
import com.zhucai.credit.valid.invoice.InvoiceValidService;

/**
 * 发票相关接口实现
 * 
 * @author hsg
 *
 */
@Service("invoiceServiceImpl")
@com.alibaba.dubbo.config.annotation.Service(version = "1.0.0")
public class InvoiceServiceImplT implements InvoiceService {
	@Autowired
	private EntAccountRepository entAccountRepository;
	@Autowired
	private CreditInvoiceRepository creditInvoiceRepository;
	@Autowired
	private CreditRecordRepository creditRecordRepository;
	@Autowired
	private InvoiceValidService invoiceValidService;
	@Resource(name = "SMS")
	private INotificationService iNotificationService;
	
	private static final Logger logger = LoggerFactory.getLogger(InvoiceServiceImplT.class);

	@Override
	public CreditInvoice checkTrue(String url, Long recordId) {
		// 发票验真开始
		logger.info("### 发票验真start url={},recordId", url, recordId);
		CreditInvoice ci = new CreditInvoice();
		try {
			// 获取字节流
			String invoiceBuffer = invoiceValidService.invoiceSign(url);
			// 判断此图片是否被验真过
			CreditInvoiceEntity findByFlow = creditInvoiceRepository.findByFlow(invoiceBuffer);

			if (findByFlow != null && !findByFlow.getCheckTrueStatus().equals(0)) {
				// 查看此发票是否被用过
				List<CreditRecordEntrity> findByInvoiceTid = creditRecordRepository.findByInvoiceTid(findByFlow.getTid());
				//查询出发票被使用并且不是这条记录时返回null
				if (CollectionUtils.isNotEmpty(findByInvoiceTid) && findByInvoiceTid.get(0).getTid().compareTo(recordId) != 0) {
					logger.warn("### 根据发票验签查询到此发票已被验真并且已被使用 发票id={}", findByFlow.getTid());
					ci.setCheckTrueStatus(2);
					ci.setRemark("根据发票验签查询到此发票已被验真并且已被使用,发票id="+findByFlow.getTid());
					return ci;
				}
				logger.info("### 此发票已验真过 invoiceBuffer={}", invoiceBuffer);
				BeanUtils.copyProperties(findByFlow, ci);
				return ci;
			}
			InviceValidResult valid = invoiceValidService.valid(url);
			
			if (valid == null) {
				logger.info("### 发票验真接口返回null url={}", url);
				ci.setCheckTrueStatus(2);
				ci.setRemark("发票验真接口返回null");
				return ci;
			}
			if (valid.getInvoicefalseCode() != null) {
				logger.info("### 发票验真接口异常 errMsg={}", valid.getResultMsg());
				// 发送短信提醒乐税金额不足
				if (valid.getInvoicefalseCode().equals("240")) {
					iNotificationService.notification("您好，当前乐税发票验真API余额不足，请及时充值");
				}
				ci.setCheckTrueStatus(2);
				ci.setRemark(valid.getResultMsg());
				return ci;
			}
			// 根据融资记录id查询发票信息
			CreditRecordEntrity cre = creditRecordRepository.findOne(recordId);
			if (cre != null && cre.getInvoiceTid() != null) {
				// 更新发票数据
				Integer coo = creditInvoiceRepository.updateCheckInvoice(cre.getInvoiceTid(), valid.getInvoiceDataCode(), valid.getInvoiceNumber(), valid.getSalesTaxpayerNum(),
						valid.getTaxpayerNumber(), valid.getTotalTaxSum(), valid.getBillingTime(), invoiceBuffer,1);
				if (coo.compareTo(1) != 0) {
					logger.error("### 发票验真成功，数据库更新失败 发票id={}", cre.getInvoiceTid());
				}
				CreditInvoiceEntity findOne = creditInvoiceRepository.findOne(cre.getInvoiceTid());
				BeanUtils.copyProperties(findOne, ci);
			} else {
				// 发票验真通过，新增发票数据
				CreditInvoiceEntity cie = new CreditInvoiceEntity();
				cie.setCheckInvoiceAmount(valid.getTotalTaxSum());
				cie.setCheckInvoiceCode(valid.getInvoiceDataCode());
				cie.setCheckInvoiceDate(valid.getBillingTime());
				cie.setCheckInvoiceNo(valid.getInvoiceNumber());
				cie.setPurUncert(valid.getTaxpayerNumber());
				cie.setSupUncert(valid.getSalesTaxpayerNum());
				cie.setCheckTrueStatus(1);
				cie.setInvoiceFlow(invoiceBuffer);
				cie.setCreTime(new Date());
				CreditInvoiceEntity save = creditInvoiceRepository.save(cie);
				BeanUtils.copyProperties(save, ci);
			}
			
		} catch (Exception e) {
			logger.error("### 发票验真异常 errMsg={}", e);
			ci.setCheckTrueStatus(2);
			ci.setRemark("发票验真异常 "+e);
			return ci;
		}

		return ci;
	}

	@Override
	public Boolean checkFrom(Long crId, Long invoiceId) {
		logger.info("### 验证发票归属start recordId={},invoiceId={}", crId, invoiceId);
		Boolean status = false;
		try {
			// 融资信息
			CreditRecordEntrity cre = creditRecordRepository.findOne(crId);
			// 发票信息
			CreditInvoiceEntity cie = creditInvoiceRepository.findOne(invoiceId);
			String purOrgNum = SqlResultUtil.getOrgNum(cie.getPurUncert());
			String supOrgNum = SqlResultUtil.getOrgNum(cie.getSupUncert());
			// 查询采购商企业信息
			EntAccountEntity purEnt = entAccountRepository.findOne(cre.getOriginator());
			EntAccountEntity supEnt = entAccountRepository.findOne(cre.getParticipator());
			if (purEnt.getOrgNum().equals(purOrgNum) && supEnt.getOrgNum().equals(supOrgNum)) {
				logger.info("### 验证发票归属成功 crId={},invoiceId={}", crId, invoiceId);
				status = true;
			} else {
				logger.info("### 验证发票归属失败 crId={},invoiceId={}", crId, invoiceId);
				status = false;
			}
		} catch (Exception e) {
			logger.error("### 验证发票归属异常 errMsg={}", e);
			return status;
		}
		return status;

	}

	@Override
	public CreditInvoice findById(Long tid) {
		// 发票信息
		CreditInvoiceEntity cie = creditInvoiceRepository.findOne(tid);
		CreditInvoice ci = new CreditInvoice();
		if (cie != null) {
			BeanUtils.copyProperties(cie, ci);
		}
		return ci;
	}

}
